#!/bin/bash -l

CONFIG_INI_FILE=$1

if ! [ -a "${CONFIG_INI_FILE}" ];
then
  echo "config not exist!"
  exit 1
fi

exportParams(){
  PARAM_FILE=$1
  ! [ -a ${PARAM_FILE} ] && return 1
  PARAMS=($(cat ${PARAM_FILE} | grep -v '#' | awk NF))
  for PARAM in "${PARAMS[@]}"
  do
    KEY=$(echo "${PARAM}" | awk -F '=' '{print $1}')
    VALUE=$(echo "${PARAM}" | awk -F '=' '{print $2}')
    eval "${KEY}=${VALUE}"
  done
}
exportParams ${CONFIG_INI_FILE}
ARCHIVED_FILE_DIR="$([ ${REMOTE_DEPLOY} == YES ] && echo ${DEPLOY_POSITION_DIR} || echo ${PROJECT_DIR}/jenkins_deploy)/${DEPLOY_FILE_DIR_NAME}/archived"

#DEPLOY_POSITION_DIR判断
if ! [ -d ${DEPLOY_POSITION_DIR} ];
then
  echo "${DEPLOY_POSITION_DIR} isn't exist,help you create it"
  mkdir -p ${DEPLOY_POSITION_DIR}
fi

#备份
if [ ${AUTO_BACKUP} == "YES" ];
then
  echo "start backups"
  if [ -d ${ARCHIVED_FILE_DIR}/${module} ];
    then
      echo "backups ${module}"
      ITEMS=($(ls "${DEPLOY_POSITION_DIR}/${module}" | grep "dist"))
      if [ ${#ITEMS[@]} -gt 0 ];
      then
        BK_DIR="${DEPLOY_POSITION_DIR}/${module}/$(date "+%Y.%m.%d")"
        mkdir -p "${BK_DIR}"
        /bin/cp -rf ${DEPLOY_POSITION_DIR}/${module}/dist* "${BK_DIR}"
      fi
    else
      echo "not exist ${module}"
  fi
fi

#覆盖旧版本
echo "overwrite old application"
if ! [ -d ${ARCHIVED_FILE_DIR}/${module} ];
then
  echo "not exist ${module}"
  exit 1
fi
if ! [ -d ${DEPLOY_POSITION_DIR}/${module} ];
then
  mkdir -p "${DEPLOY_POSITION_DIR}/${module}"
fi
/bin/cp -rf ${ARCHIVED_FILE_DIR}/${module}/dist* "${DEPLOY_POSITION_DIR}/${module}"

#解压
unzip -o ${DEPLOY_POSITION_DIR}/${module}/dist.zip -d ${DEPLOY_POSITION_DIR}/${module}/ >/dev/null
